﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BoriPeter.NutritionManager.WebFormsClient
{
    public partial class Verify : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(Request.QueryString["user"]))
            {
                InformationLabel.Text = "Missing username";
            }
            else if (Membership.GetUser(Request.QueryString["user"]) == null)
            {
                InformationLabel.Text = "The username doesn't exist in the database";
            }
            else if (String.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                InformationLabel.Text = "An invalid ID value was passed in through the querystring.";
            }
            else
            {
                if (Request.QueryString["ID"] == GenerateHash(Membership.GetUser(Request.QueryString["user"])))
                {
                    var userInfo = Membership.GetUser(Request.QueryString["user"]);
                    userInfo.IsApproved = true;
                    Membership.UpdateUser(userInfo);

                    InformationLabel.Text = "Dear " +userInfo.UserName + ", your account is now ready to use";
                }
                else
                {
                    InformationLabel.Text = "An invalid ID value was passed in through the querystring.";
                }
                //InformationLabel.Text = Request.QueryString["ID"] + " *** " + GenerateHash(Membership.GetUser(Request.QueryString["user"]));
            }
        }

        public string GenerateHash(MembershipUser userInfo)
        {
            string code = userInfo.Email + userInfo.CreationDate.ToString();
            string salt = userInfo.ProviderUserKey.ToString() + "skftwbdh";
            Rfc2898DeriveBytes Hasher = new Rfc2898DeriveBytes(code,
                System.Text.Encoding.Default.GetBytes(salt), 10000);
            return Uri.EscapeUriString(Convert.ToBase64String(Hasher.GetBytes(25)));
        }
    }
}